package com.coding.config;

import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;


@Configuration
public class RedisConfig {
    // 需要一个工厂建造器
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory builder) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(builder);  // 设置连接工厂

        // 进行序列化
        FastJsonRedisSerializer<String> stringFastJsonRedisSerializer = new
                FastJsonRedisSerializer<>(String.class);
        // 对value值进行序列化
        redisTemplate.setValueSerializer(stringFastJsonRedisSerializer);
        // 对key值进行序列化
        redisTemplate.setKeySerializer(new StringRedisSerializer());

        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(stringFastJsonRedisSerializer);

        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
}
